package com.agileboot.attendance.domain.settlement.model;

import com.agileboot.attendance.domain.settlement.dto.SettlementRequest;
import com.agileboot.attendance.domain.settlement.entity.AttSettlementEntity;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.infrastructure.user.AuthenticationUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 结算单领域模型
 */
@Data
@NoArgsConstructor
public class SettlementModel {

    private AttSettlementEntity entity;

    public SettlementModel(AttSettlementEntity entity) {
        this.entity = entity;
    }

    /**
     * 从请求对象加载数据
     */
    public void loadFromRequest(SettlementRequest request) {
        if (entity == null) {
            entity = new AttSettlementEntity();
        }
        BeanUtils.copyProperties(request, entity);
    }

    /**
     * 校验字段
     */
    public void checkFields() {
        // 1. 基础字段校验
        if (entity.getTotalAmount() == null || entity.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ApiException(ErrorCode.Client.COMMON_REQUEST_PARAMETERS_INVALID, "结算金额必须大于0");
        }
        if (entity.getCreateTime() == null) {
            throw new ApiException(ErrorCode.Client.COMMON_REQUEST_PARAMETERS_INVALID, "创建时间不能为空");
        }

        // 2. 验收单关联校验
        if (StringUtils.isBlank(entity.getAcceptanceIds())) {
            throw new ApiException(ErrorCode.Client.COMMON_REQUEST_PARAMETERS_INVALID, "必须选择验收单");
        }

        // 3. 验证验收单状态
        List<String> acceptanceIds = Arrays.asList(entity.getAcceptanceIds().split(","));
        checkAcceptanceStatus(acceptanceIds);
    }

    /**
     * 校验验收单状态
     */
    private void checkAcceptanceStatus(List<String> acceptanceIds) {
        // TODO: 调用验收单服务检查：
        // 1. 验收单是否存在
        // 2. 验收单是否已通过验收
        // 3. 验收单是否已被结算
        // 4. 验收单金额总和是否与结算金额一致
    }

    /**
     * 插入数据
     */
    public void insert() {
        entity.setCreatorId(AuthenticationUtils.getUserId());
        entity.setDeleted(false);
        // 调用数据库服务插入数据
    }

    /**
     * 更新数据
     */
    public void update() {
        entity.setUpdaterId(AuthenticationUtils.getUserId());
        // 调用数据库服务更新数据
    }

    /**
     * 删除数据
     */
    public void delete() {
        entity.setDeleted(true);
        entity.setUpdaterId(AuthenticationUtils.getUserId());
        // 调用数据库服务删除数据
    }
}
